#include "stdio.h"
#include "unistd.h"
#include <sys/time.h>
#include <pthread.h>
#include <stdlib.h>

// static int data = 0;

// 长时间计算的函数
int cal_sqr(int n) {

    sleep(1);
    return n * n;
}

void *cal_thread_fun(void *arg) {
    int num =  *(int *)arg;
    int *result = malloc(sizeof(int));
    *result = cal_sqr(num);
    // return result;
    pthread_exit(result); // 结束当前线程
}

int main(int argc, char const *argv[])
{
    int items[5] = {1, 2, 3, 4, 5};
    int sqrs[5];

    struct timeval start, end;
    gettimeofday(&start, NULL);
    pthread_t   pts[5];
    for (int i = 0; i < 5; i++)
    {
        // sqrs[i] = cal_sqr(items[i]);
        pthread_create(pts+i, NULL, cal_thread_fun, &items[i]);
    }

    for (int i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(pts[i], &result);
        sqrs[i] = *(int *)result;
    }
    
    
    gettimeofday(&end, NULL);
    printf("time: %ld\n", end.tv_sec - start.tv_sec);

    int sum = 0;
    for (int i = 0; i < 5; i++)
    {
        sum += sqrs[i];
    }

    printf("sum: %d\n", sum);

    return 0;
}
